package com.manor.paradise.activity

import android.util.Log
import android.view.View
import android.widget.ImageView
import com.gyf.immersionbar.ktx.immersionBar
import com.manor.common.activity.AbsActivity
import com.manor.common.dialog.XCodeImgPopup
import com.manor.common.http.JCommonHttpUtil
import com.manor.common.http.JHttpCallback
import com.manor.common.ktx.toBean
import com.manor.common.utils.*
import com.manor.paradise.R
import com.manor.paradise.adapter.LybTaskDetailsAdapter
import com.manor.paradise.bean.AssetsBean
import com.manor.paradise.bean.DoIsTaskBean
import com.manor.paradise.bean.HoneyBean
import com.manor.paradise.bean.ParadiseInfoBean
import com.manor.paradise.dialog.CompletePopup
import com.manor.paradise.http.ElvesHttpConst
import com.manor.paradise.http.ElvesHttpUtil
import com.mob.adsdk.AdSdk
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.android.synthetic.main.lyb_activity_do_task.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.math.BigDecimal

class LybDoTaskActivity : AbsActivity() {
    private var pageNum = 1
    private val mIvList = arrayListOf<ImageView>()
    private val mList = arrayListOf<HoneyBean.RecordsBean>()
    private val mAdapter by lazy {
        LybTaskDetailsAdapter(mList)
    }
    override fun getLayoutId() = R.layout.lyb_activity_do_task
    override fun main() {
        super.main()
        immersionBar {
            statusBarColor(R.color.transparent)
            titleBarMarginTop(mTitleSpace)
            statusBarDarkFont(false)
        }
        mTaskProgressSb.isEnabled = false
        mTaskDetailsRv.adapter = mAdapter
        mIvList.add(mTask1Iv)
        mIvList.add(mTask2Iv)
        mIvList.add(mTask3Iv)
        mIvList.add(mTask4Iv)
        mIvList.add(mTask5Iv)
        setClick(mTask1Iv, mTask2Iv, mTask3Iv, mTask4Iv, mTask5Iv, mTask6Iv, mCloseIv)
        mTaskDetailsSrl.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                pageNum++
                setData()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageNum = 1
                setData()
            }
        })
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        if (v?.id == R.id.mCloseIv){
            finish()
        }else{
            showWaitingDialog(true)
            doAdvert()
        }
    }
    private fun getProperty(){
        ElvesHttpUtil.getParadiseInfo( object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code != 200) {
                    ToastUtil.show(msg)
                    return
                }

                val paradiseInfoBean: ParadiseInfoBean = GsonUtil.gsonToBean(info, ParadiseInfoBean::class.java)
                mDailyProductionTv?.content(paradiseInfoBean.todayCrystalOre)//日产量
                mAlreadyGotMlTv?.content(paradiseInfoBean.crystalOre)//已有米粒
                mPowerTv?.content(paradiseInfoBean.crystal)//能量
                KLog.e("json", paradiseInfoBean)
                mTaskCountTv?.text = paradiseInfoBean.todayHoney.frontAndBack("获取饲料 （", "/5）")
                mAdvancedTaskTv?.text = paradiseInfoBean.todaySeniorHoney.frontAndBack("获取高级饲料 （" , "/1）")

                for (i in mIvList.indices) {
                    if (i < paradiseInfoBean.todayHoney.toInt()) {
                        mIvList[i].isEnabled = false
                        mIvList[i].setImageResource(R.drawable.task_unfinished)
                    }
                }
            }
            override fun onError() {
                super.onError()
            }
        })
    }
    private fun setInfoData() {
        ElvesHttpUtil.getAssetsValue(object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code != 200) {
                    ToastUtil.show(msg)
                    return
                }
                var assetsBean: AssetsBean = GsonUtil.gsonToBean<AssetsBean>(info, AssetsBean::class.java)
                if (assetsBean.isBseniorHoney) {
                    mAdvancedTaskLayout?.v(true)
                    var num = (assetsBean.todayHoney + assetsBean.todaySeniorHoney).toBigDecimal()
                    var b = num.divide(BigDecimal("6"), 2, BigDecimal.ROUND_DOWN).multiply(BigDecimal("100")).intValueExact()
                    mTaskProgressSb.progress = b
                } else {
                    mAdvancedTaskLayout?.v(false)
                    mTaskProgressSb?.progress = BigDecimal(assetsBean.todayHoney.toString()).divide(BigDecimal("5"), 2, BigDecimal.ROUND_DOWN).multiply(BigDecimal("100")).intValueExact()
                }
                mProgressTv.content(mTaskProgressSb?.progress.back("%"))
                mTask6Iv.isSelected = assetsBean.todaySeniorHoney.toString() == "1"
            }
        })
    }
    private fun setData() {
        ElvesHttpUtil.getTaskList(pageNum, object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code != 200) {
                    ToastUtil.show(msg)
                    return
                }
                if (StringUtil.isEmpty(info)) {
                    ///ToastUtil.show("服务器返回错误")
                    return
                }
                var shopListBean: HoneyBean = GsonUtil.gsonToBean<HoneyBean>(info, HoneyBean::class.java)
                KLog.e("json", shopListBean)
                if (pageNum == 1) {
                    mList.clear()
                    mList.addAll(shopListBean.records)
                    mTaskDetailsSrl?.finishRefresh()
                } else {
                    mList.addAll(shopListBean.records)
                    mTaskDetailsSrl?.finishLoadMore()
                }
                mAdapter.notifyDataSetChanged()
            }
        })
    }
    /**
     * 查看视频激励广告
     */
    private fun doAdvert() {
        var advReward = false
        AdSdk.getInstance().loadRewardVideoAd(this, "rv1", false,
                object : AdSdk.RewardVideoAdListener {
                    override fun onAdLoad(id: String?) {
                        dismissWaitingDialog()
                    }

                    override fun onVideoCached(id: String?) {}

                    override fun onReward(id: String?) {
                        advReward = true
                    }

                    override fun onAdShow(id: String?) {
                        dismissWaitingDialog()
                    }

                    override fun onAdClick(id: String?) {}

                    override fun onVideoComplete(id: String?) {}

                    override fun onAdClose(id: String?) {
                        if (advReward) {
                            advReward = false
                            getReward()
                        }
                    }
                    override fun onError(id: String?, p1: Int, p2: String?) {
                        Log.e("错误码：", "错误码: $p1   错误信息: $p2")
                        showT("")
                    }
                })

    }
    private fun getReward() {
        JCommonHttpUtil.doTaskIsFinish("2", object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String?, info: String?) {
                val bean = info?.toBean<DoIsTaskBean>()
                if (bean?.bfinished == "false" && bean?.bopenDoTask == "true") {

                    if (bean.bneedVerification == "true") {

                        val timeCount = bean.timeRemaining?.toIntOrNull() ?: 60
                        val vCode = bean.verifyCode ?: ""
                        val timeStamp =  bean.timeStamp ?: ""
                        XCodeImgPopup.load(this@LybDoTaskActivity, vCode, timeStamp, "2", timeCount) { ix ->
                            CompletePopup.load(this@LybDoTaskActivity){
                                GlobalScope.launch {
                                    delay(1000)
                                    runOnUiThread {
                                        getNetData()
                                    }
                                }
                            }
                        }
                    } else {
                        doTask(bean?.verifyCode ?: "", bean?.timeStamp ?: "", "", "")
                    }
                } else {
                    msg?.let { ToastUtil.show(it) }
                }
            }
        })
    }

    private fun doTask(code: String, timeStamp: String, random: String, imgCode: String) {
        JCommonHttpUtil.getAdTask("", code, timeStamp, random, imgCode, "2", object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code == 1509) { }
                if (code != 200) {
                    ToastUtil.show(msg)
                    return
                }
                CompletePopup.load(this@LybDoTaskActivity){
                    GlobalScope.launch {
                        delay(1000)
                        runOnUiThread {
                            getNetData()
                        }
                    }
                }
            }
        })
    }

    override fun onResume() {
        super.onResume()
        getNetData()
    }

    override fun onDestroy() {
        ElvesHttpUtil.cancel(ElvesHttpConst.POST_OPEN_PAGE_VALUE)
        ElvesHttpUtil.cancel(ElvesHttpConst.POST_OPEN_USER_ANIMA_LIST)
        super.onDestroy()
    }
    private fun getNetData(){
        pageNum = 1
        getProperty()
        setInfoData()
        setData()
    }
}